import {toast} from "../../utils/tool";
import EventBus from "../../utils/eventBus";
import {BASE_URL} from "../../constant/index";

const app = getApp()
Page({
    data: {
        storeList: [],
        type: '',
        loading: false,
        baseUrl: BASE_URL,
    },
    confirmChange(e) {
        if (this.data.loading) return
        this.data.loading = true
        const {store} = e.currentTarget.dataset
        app.setFirst(store)
        const {type} = this.data
        if (type !== 'back') {
            app.globalData.changeStore = store
            EventBus.$emit('change_store_success', store)
        }
        toast({title: '选择成功'}, () => {
            this.data.loading = false
            if (type === 'back') return wx.navigateBack()
            wx.switchTab({
                url: "/pages/index/index",
            })
        })
    },
    // 打开地图
    openMap: function (e) {
        let mapdata = e.currentTarget.dataset.mapdata
        let arr = mapdata.lat.split(",")
        var lat = parseFloat(arr[1]),
            lon = parseFloat(arr[0]),
            firstStore = this.data.firstStore;
        if (!lat || !lon) {
            return false;
        }
        wx.openLocation({
            latitude: lon,
            longitude: lat,
            scale: 15,
            name: mapdata.name,
            address: mapdata.address,
            success: function (res) {
            },
            fail: function (res) {
            }
        })
    },
    initData(e) {
        app.ajax({
            url: "/api/room/storelist",
            data: {lat: e.lat, lon: e.lon},
            success: res => {
                if (!res.data) res.data = []
                const {code, data, msg} = res
                if (code !== 1) toast({title: msg})
                this.setData({
                    storeList: data.map(item => {
                        const {image} = item
                        item.image = BASE_URL + image
                        return item
                    })
                })
            }
        })
    },
    previewImage(ev) {
        const {image} = ev.currentTarget.dataset
        if (!image) return
        wx.previewImage({urls: [image]})
    },
    callPhone(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone,
            success: function () {
            },
        })
    },
    onLoad(options) {
        let location = wx.getStorageSync('location')
        if (options.hasOwnProperty('type')) {
            const {type} = options
            this.data.type = type
        }
        this.initData(location)
    },

})
